
import { defineStore } from 'pinia'
import { MD5 } from '@/utils/md5'
import { storage } from '@/utils/storage'
import { URLS_STORE } from '@/enum';
const useBookmarkStore = defineStore('bookmark', {
    state: () => ({
        bookmarkList: []
    }),
    getters: {

    },
    actions: {
        onLoadBookmarkList() {
            this.getBookmarkListFromDb()
        },
        createBookmark(bookmark) {
            bookmark.id = MD5(bookmark.url);
            storage.set({ [URLS_STORE]: [...this.bookmarkList, bookmark] }, () => {
                console.log('Bookmark list saved to storage');
            }).then(() => {
                this.bookmarkList.push(bookmark)
            })

        },
        deleteBookmark(id) {
            this.bookmarkList = this.bookmarkList.filter(item => item.id !== id)
            storage.set({ [URLS_STORE]: this.bookmarkList }, () => {
                console.log('Bookmark list saved to storage');
            }).then(() => {
                this.bookmarkList = this.bookmarkList.filter(item => item.id !== id)
            })
        },
        // 刷新
        refreshBookmarkList() {
            this.getBookmarkListFromDb()
        },
        getBookmarkListFromDb() {
            storage.get([URLS_STORE], (result) => {
                console.log("result", result);
                if (result[URLS_STORE]) {
                    this.bookmarkList = result[URLS_STORE];
                } else {
                    this.bookmarkList = [];
                }
            });
        }
    },

})
export default useBookmarkStore;